<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\Store;
use App\Models\StoreCategory;
use App\Models\StoreGoods;
use App\Models\StoreGoodsCategory;
use App\Models\GoodsCategory;
use App\Models\GoodsCategoryRelation;
use App\Models\Category;
use App\Models\Address;
use App\Models\HhmGoods;
use App\Models\HhmCategory;
use App\Models\HhmGoodsCategory;
use App\Models\StoreCashierSwitchCode;
use App\Models\StoreCashierSwitchCodeGroupRelation;
use App\Models\StoreCashierSwitchCodeGroupProperties;
use App\Services\ImageUrlService;
use Exception;

class MerchantApiController extends BaseApiController
{
    /**
     * 格式化距离显示
     * 注意：distance参数已经是公里单位，不需要再除以1000
     */
    private function formatDistance($distance)
    {
        if ($distance < 1) {
            // 小于1公里，显示为米
            return round($distance * 1000) . 'm';
        } else {
            // 大于等于1公里，显示为公里
            return round($distance, 1) . 'km';
        }
    }

    /**
     * 根据dispatch_type数组生成配送方式文本
     *
     * @param array|string|int $dispatchType 配送类型数组/字符串/数字
     * @return array 配送方式文本数组
     */
    private function getDispatchText($dispatchType)
    {
        if (is_numeric($dispatchType)) {
            $dispatchType = [(int) $dispatchType];
        } elseif (is_string($dispatchType)) {
            $decoded = json_decode($dispatchType, true);
            if (is_array($decoded)) {
                $dispatchType = $decoded;
            } elseif (is_numeric($dispatchType)) {
                $dispatchType = [(int) $dispatchType];
            } else {
                $dispatchType = [];
            }
        } elseif (! is_array($dispatchType)) {
            $dispatchType = [];
        }
        if (empty($dispatchType)) {
            return [];
        }
        $typeMap = [
            1  => '快递',
            2  => '上门自提',
            3  => '门店配送',
            12 => '门店自提点提货',
        ];
        $result = [];
        foreach ($dispatchType as $type) {
            if (isset($typeMap[$type])) {
                $result[] = $typeMap[$type];
            }
        }
        return $result;
    }

    /**
     * 查询门店支持的置换类型
     *
     * @param int $storeId 门店ID
     * @return array 置换类型数组
     */
    private function getStoreSwapTypes($storeId)
    {
        $swapTypes = [];
        try {
            $relations = StoreCashierSwitchCodeGroupRelation::where('store_id', $storeId)
                ->where('state', 1)
                ->get();
            if (! $relations->isEmpty()) {
                $groupPropertieIds = $relations->pluck('group_propertie_id')->filter()->unique()->toArray();
                if (! empty($groupPropertieIds)) {
                    $properties = StoreCashierSwitchCodeGroupProperties::whereIn('id', $groupPropertieIds)
                        ->where('state', 1)
                        ->get(['in_type', 'in_type_name']);
                    foreach ($properties as $prop) {
                        $swapTypes[] = [
                            'in_type'      => $prop->in_type,
                            'in_type_name' => $prop->in_type_name,
                        ];
                    }
                }
            }
        } catch (\Exception $e) {
            $swapTypes = [];
        }
        return $swapTypes;
    }

    /**
     * 批量查询门店支持的置换类型
     * 避免N+1查询问题
     *
     * @param array $storeIds 门店ID数组
     * @return array 门店ID => 置换类型数组的映射
     */
    private function getStoreSwapTypesBatch($storeIds)
    {
        if (empty($storeIds)) {
            return [];
        }

        $result = [];
        
        try {
            // 批量查询所有门店的置换类型关系
            $relations = StoreCashierSwitchCodeGroupRelation::whereIn('store_id', $storeIds)
                ->where('state', 1)
                ->get();

            if ($relations->isEmpty()) {
                // 所有门店都没有置换类型
                foreach ($storeIds as $storeId) {
                    $result[$storeId] = [];
                }
                return $result;
            }

            // 获取所有分组属性ID
            $groupPropertieIds = $relations->pluck('group_propertie_id')->filter()->unique()->toArray();
            
            if (!empty($groupPropertieIds)) {
                // 批量查询分组属性
                $properties = StoreCashierSwitchCodeGroupProperties::whereIn('id', $groupPropertieIds)
                    ->where('state', 1)
                    ->get(['id', 'in_type', 'in_type_name'])
                    ->keyBy('id');

                // 按门店分组
                $storeRelationsMap = $relations->groupBy('store_id');
                
                // 构建结果
                foreach ($storeIds as $storeId) {
                    $storeRelations = $storeRelationsMap->get($storeId, collect());
                    $swapTypes = [];
                    $seenInTypes = []; // 用于去重
                    
                    foreach ($storeRelations as $relation) {
                        $property = $properties->get($relation->group_propertie_id);
                        if ($property) {
                            // 去重：同一个 in_type 只添加一次
                            if (!in_array($property->in_type, $seenInTypes)) {
                                $swapTypes[] = [
                                    'in_type'      => $property->in_type,
                                    'in_type_name' => $property->in_type_name,
                                ];
                                $seenInTypes[] = $property->in_type;
                            }
                        }
                    }
                    
                    $result[$storeId] = $swapTypes;
                }
            } else {
                // 没有有效的分组属性
                foreach ($storeIds as $storeId) {
                    $result[$storeId] = [];
                }
            }
        } catch (\Exception $e) {
            \Log::error('[置换类型批量查询] 查询失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            // 出错时返回空数组
            foreach ($storeIds as $storeId) {
                $result[$storeId] = [];
            }
        }

        return $result;
    }

    /**
     * 批量获取门店的供货商信息（用于判断上门自提）
     * @param array $storeIds 门店ID数组
     * @return array 门店供货商映射数组
     */
    private function getBatchStorePickupVendors($storeIds)
    {
        if (empty($storeIds)) {
            return [];
        }

        $pickupVendorsMap = [];
        
        try {
            // 批量查询自提点-供货商关系
            $pickupPoints = \App\Models\PickupPointVendor::whereIn('store_id', $storeIds)->get(['store_id', 'vendor_id']);
            
            if ($pickupPoints->isEmpty()) {
                // 所有门店都没有供货商
                return array_fill_keys($storeIds, ['supports_pickup' => false, 'vendor_ids' => [], 'vendors' => []]);
            }

            // 按门店分组
            $pointsByStore = $pickupPoints->groupBy('store_id');
            
            // 获取所有供货商ID
            $allVendorIds = $pickupPoints->pluck('vendor_id')->unique()->toArray();
            
            // 批量查询供货商信息（只查询status=1的活跃供货商）
            $vendors = [];
            if (!empty($allVendorIds)) {
                $vendors = \App\Models\Vendor::whereIn('id', $allVendorIds)
                    ->where('status', 1) // 只查询活跃供货商
                    ->select('id', 'supplier_name', 'mobile')
                    ->get()
                    ->keyBy('id');
            }
            
            // 构建结果
            foreach ($storeIds as $storeId) {
                if (isset($pointsByStore[$storeId])) {
                    $vendorIds = $pointsByStore[$storeId]->pluck('vendor_id')->toArray();
                    $vendorList = [];
                    
                    // 只添加活跃的供货商
                    foreach ($vendorIds as $vendorId) {
                        if (isset($vendors[$vendorId])) {
                            $vendor = $vendors[$vendorId];
                            $vendorList[] = [
                                'id' => $vendor->id,
                                'supplier_name' => $vendor->supplier_name,
                                'mobile' => $vendor->mobile,
                            ];
                        }
                    }
                    
                    $pickupVendorsMap[$storeId] = [
                        'supports_pickup' => !empty($vendorList),
                        'vendor_ids' => $vendorIds,
                        'vendors' => $vendorList,
                    ];
                } else {
                    $pickupVendorsMap[$storeId] = [
                        'supports_pickup' => false,
                        'vendor_ids' => [],
                        'vendors' => [],
                    ];
                }
            }
        } catch (\Exception $e) {
            // 出错时返回默认值
            $pickupVendorsMap = array_fill_keys($storeIds, ['supports_pickup' => false, 'vendor_ids' => [], 'vendors' => []]);
        }
        
        return $pickupVendorsMap;
    }

    /**
     * 获取置换支持类型列表
     *
     * @return JsonResponse
     */
    public function swapTypes(): JsonResponse
    {
        try {
            $swapTypes = StoreCashierSwitchCode::getSwapTypes();

            return response()->json([
                'code' => 200,
                'message' => '获取成功',
                'data' => $swapTypes
            ]);

        } catch (\Exception $e) {
            \Log::error('获取置换支持类型失败', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 500,
                'message' => '获取置换支持类型失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 获取同城商家列表
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $page = $this->getParam($request, 'page', 1);
            $limit = $this->getParam($request, 'limit', 10);
            $category = $this->getParam($request, 'category', 'all');
            $distance = $this->getParam($request, 'distance', 10);

            // 模拟商家数据
            $merchants = [
                [
                    'id' => 1,
                    'name' => '老王烤肉店',
                    'category' => '餐饮美食',
                    'rating' => 4.5,
                    'address' => '海淀区中关村大街128号',
                    'distance' => 1.2,
                    'image' => 'https://example.com/bbq.jpg',
                    'tags' => ['置换支持', '沐浴露', '茶包'],
                    'status' => '营业中',
                    'business_hours' => '10:00-22:00'
                ],
                [
                    'id' => 2,
                    'name' => '星巴克咖啡',
                    'category' => '饮品甜品',
                    'rating' => 4.8,
                    'address' => '朝阳区建国路88号',
                    'distance' => 2.5,
                    'image' => 'https://example.com/starbucks.jpg',
                    'tags' => ['置换支持', '茶包'],
                    'status' => '营业中',
                    'business_hours' => '07:00-22:00'
                ],
                [
                    'id' => 3,
                    'name' => '美甲沙龙',
                    'category' => '美容美甲',
                    'rating' => 4.6,
                    'address' => '西城区西单北大街15号',
                    'distance' => 3.1,
                    'image' => 'https://example.com/nail.jpg',
                    'tags' => ['置换支持', '沐浴露'],
                    'status' => '营业中',
                    'business_hours' => '09:00-21:00'
                ],
                [
                    'id' => 4,
                    'name' => '小龙虾餐厅',
                    'category' => '餐饮美食',
                    'rating' => 4.7,
                    'address' => '朝阳区三里屯路19号',
                    'distance' => 4.0,
                    'image' => 'https://example.com/crayfish.jpg',
                    'tags' => ['置换支持', '茶包'],
                    'status' => '营业中',
                    'business_hours' => '11:00-23:00'
                ]
            ];

            // 分页处理
            $total = count($merchants);
            $offset = ($page - 1) * $limit;
            $data = array_slice($merchants, $offset, $limit);

            return response()->json([
                'code' => 200,
                'message' => '获取成功',
                'data' => [
                    'list' => $data,
                    'pagination' => [
                        'current_page' => (int)$page,
                        'per_page' => (int)$limit,
                        'total' => $total,
                        'last_page' => ceil($total / $limit)
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '服务器错误',
                'data' => null
            ], 500);
        }
    }

    /**
     * 获取商家详情
     * 
     * 性能优化说明：
     * 1. 使用子查询减少JOIN操作
     * 2. 一次性获取所有分类和商品数据
     * 3. 使用内存映射替代多次数据库查询
     * 4. 只查询必要的字段，减少数据传输
     * 5. 建议在相关表上添加索引：
     *    - ims_yz_store_goods_category: (store_id, category_id)
     *    - ims_yz_goods_category: (goods_id, category_id)
     *    - ims_yz_store_goods: (store_id, goods_id)
     *    - ims_yz_goods: (id, is_deleted)
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function detail(Request $request)
    {
        \Log::info('[商家详情] ========== 开始处理请求 ==========');
        \Log::info('[商家详情] 接收到的原始请求:', $request->all());
        
        try {
            // 获取参数
            $storeId = $this->getParam($request, 'store_id') ?: $this->getParam($request, 'id');
            
            \Log::info('[商家详情] 解析到的门店ID:', ['store_id' => $storeId]);
            
            if (!$storeId) {
                \Log::warning('[商家详情] 门店ID为空');
                return response()->json([
                    'code' => 400,
                    'message' => '商家ID不能为空',
                    'data' => null
                ]);
            }

            // 查询商家信息（优化：只查询需要的字段）
            \Log::info('[商家详情] 开始查询门店信息', ['store_id' => $storeId]);
            
            $store = Store::select([
                'id', 'store_name', 'thumb', 'address', 'mobile', 'business_hours_start', 
                'business_hours_end', 'store_introduce', 'longitude', 'latitude', 
                'operating_state', 'affiche', 'specify_show', 'province_id', 'city_id', 
                'district_id', 'dispatch_type'
            ])
                ->where('id', $storeId)
                ->where('is_hide', 0)
                ->first();
            
            \Log::info('[商家详情] 门店查询结果:', ['found' => $store ? 'yes' : 'no']);

            if (!$store) {
                \Log::error('[商家详情] 门店不存在', ['store_id' => $storeId]);
                return response()->json([
                    'code' => 404,
                    'message' => '商家不存在',
                    'data' => null
                ]);
            }
            
            \Log::info('[商家详情] 门店基本信息:', [
                'id' => $store->id,
                'store_name' => $store->store_name,
                'operating_state' => $store->operating_state
            ]);

            // 移除商家分类信息查询，只保留categories字段
            
            // 查询省市区名称
            $provinceName = '';
            $cityName = '';
            $districtName = '';
            
            if ($store->province_id) {
                $province = Address::find($store->province_id);
                $provinceName = $province ? $province->areaname : '';
            }
            if ($store->city_id) {
                $city = Address::find($store->city_id);
                $cityName = $city ? $city->areaname : '';
            }
            if ($store->district_id) {
                $district = Address::find($store->district_id);
                $districtName = $district ? $district->areaname : '';
            }
            
            // 生成配送方式文本
            $dispatchType = $store->dispatch_type;
            $dispatchText = $this->getDispatchText($dispatchType);
            
            // 优化查询：一次性获取所有需要的数据（使用新表结构）
            try {
                \Log::info('[商家详情] 开始查询分类和商品数据');
                
                // 1. 一次性查询该门店的所有分类（包含层级关系）
                $categories = HhmCategory::where('store_id', $storeId)
                    ->where('enabled', 1)
                    ->orderBy('display_order', 'asc')
                    ->get();
                
                \Log::info('[商家详情] 分类查询完成', [
                    'categories_count' => $categories->count(),
                    'categories_data' => $categories->toArray()
                ]);
                
                // 2. 一次性查询该门店的所有商品
                \Log::info('[商家详情] 开始查询商品', ['store_id' => $storeId]);
                
                $storeGoods = HhmGoods::where('store_id', $storeId)
                    ->where('status', 1)  // 只查询上架商品
                    ->where('is_deleted', 0)  // 只查询未删除商品
                    ->get();
                
                \Log::info('[商家详情] 商品查询完成', [
                    'goods_count' => $storeGoods->count(),
                    'goods_data' => $storeGoods->toArray()
                ]);
                
                // 2.5 一次性查询所有有规格商品的规格信息
                $goodsIds = $storeGoods->pluck('id')->toArray();
                
                \Log::info('[商家详情] 提取商品ID列表', ['goods_ids' => $goodsIds]);
                
                // 查询规格组
                $specsMap = \DB::table('ims_hhm_goods_spec')
                    ->whereIn('goods_id', $goodsIds)
                    ->orderBy('display_order', 'asc')
                    ->get()
                    ->groupBy('goods_id');
                
                \Log::info('[商家详情] 规格组查询完成', ['specs_count' => $specsMap->count()]);
                
                // 查询规格项
                $specIds = [];
                foreach ($specsMap as $specs) {
                    foreach ($specs as $spec) {
                        $specIds[] = $spec->id;
                    }
                }
                
                \Log::info('[商家详情] 提取规格组ID列表', ['spec_ids' => $specIds]);
                
                $specItemsMap = \DB::table('ims_hhm_goods_spec_item')
                    ->whereIn('spec_id', $specIds)
                    ->orderBy('display_order', 'asc')
                    ->get()
                    ->groupBy('spec_id');
                
                \Log::info('[商家详情] 规格项查询完成', ['spec_items_count' => $specItemsMap->count()]);
                
                // 查询SKU选项
                $optionsMap = \DB::table('ims_hhm_goods_option')
                    ->whereIn('goods_id', $goodsIds)
                    ->get()
                    ->groupBy('goods_id');
                
                \Log::info('[商家详情] SKU选项查询完成', ['options_count' => $optionsMap->count()]);
                
                // 3. 一次性查询商品分类关联，使用JOIN优化
                \Log::info('[商家详情] 开始查询商品-分类关联');
                
                $goodsCategoryMap = \DB::table('ims_hhm_goods_category as gc')
                    ->join('ims_hhm_goods as g', 'gc.goods_id', '=', 'g.id')
                    ->where('g.store_id', $storeId)
                    ->where('g.status', 1)
                    ->where('g.is_deleted', 0)
                    ->select('gc.category_id', 'gc.goods_id')
                    ->get()
                    ->groupBy('category_id')
                    ->map(function($items) {
                        return $items->pluck('goods_id')->toArray();
                    });
                
                \Log::info('[商家详情] 商品-分类关联查询完成', [
                    'category_map_count' => $goodsCategoryMap->count(),
                    'category_map_data' => $goodsCategoryMap->toArray()
                ]);
                
                // 4. 构建分类层级结构
                \Log::info('[商家详情] 开始构建分类层级结构');
                
                $categoriesData = [];
                $firstCategories = $categories->where('parent_id', 0);
                $secondCategories = $categories->where('parent_id', '>', 0);
                
                \Log::info('[商家详情] 分类层级统计', [
                    'first_categories_count' => $firstCategories->count(),
                    'second_categories_count' => $secondCategories->count()
                ]);
                
                if ($firstCategories->count() > 0) {
                    $categoriesData = $firstCategories->map(function($firstCat) use ($secondCategories, $storeGoods, $goodsCategoryMap, $specsMap, $specItemsMap, $optionsMap, $storeId) {
                        \Log::info("[商家详情] 处理一级分类: {$firstCat->name}", ['category_id' => $firstCat->id]);
                        
                        $children = $secondCategories->where('parent_id', $firstCat->id)->map(function($secondCat) use ($storeGoods, $goodsCategoryMap, $specsMap, $specItemsMap, $optionsMap, $storeId) {
                            \Log::info("[商家详情] 处理二级分类: {$secondCat->name}", ['category_id' => $secondCat->id]);
                            
                            // 从映射中获取该分类的商品ID列表
                            $categoryGoodsIds = $goodsCategoryMap->get($secondCat->id, []);
                            
                            \Log::info("[商家详情] 二级分类 {$secondCat->name} 的商品ID", [
                                'category_id' => $secondCat->id,
                                'goods_ids' => $categoryGoodsIds
                            ]);
                            
                            // 构建商品列表
                            $goodsList = collect();
                            if (!empty($categoryGoodsIds)) {
                                $goodsList = $storeGoods->whereIn('id', $categoryGoodsIds)
                                    ->map(function($goods) use ($specsMap, $specItemsMap, $optionsMap) {
                                        // 计算实际显示销量
                                        $totalSales = ($goods->show_sales ?? 0) + ($goods->real_sales ?? 0) + ($goods->virtual_sales ?? 0);
                                        
                                        // 处理时间字段（兼容整型时间戳和Carbon对象）
                                        $createdAt = '';
                                        $updatedAt = '';
                                        
                                        if ($goods->created_at) {
                                            if (is_numeric($goods->created_at)) {
                                                $createdAt = date('Y-m-d H:i:s', $goods->created_at);
                                            } elseif (is_object($goods->created_at)) {
                                                $createdAt = $goods->created_at->format('Y-m-d H:i:s');
                                            }
                                        }
                                        
                                        if ($goods->updated_at) {
                                            if (is_numeric($goods->updated_at)) {
                                                $updatedAt = date('Y-m-d H:i:s', $goods->updated_at);
                                            } elseif (is_object($goods->updated_at)) {
                                                $updatedAt = $goods->updated_at->format('Y-m-d H:i:s');
                                            }
                                        }
                                        
                                        $result = [
                                            'id' => $goods->id,
                                            'title' => $goods->title ?? '',
                                            'thumb' => ImageUrlService::processImageUrl($goods->thumb),
                                            'price' => $goods->price ?? '0.00',
                                            'market_price' => $goods->market_price ?? '0.00',
                                            'cost_price' => $goods->cost_price ?? '0.00',
                                            'stock' => $goods->stock ?? 0,
                                            'sku' => $goods->sku ?? '',
                                            'description' => $goods->description ?? '',
                                            'has_option' => $goods->has_option ?? 0,
                                            'option_count' => $goods->option_count ?? 0,
                                            'is_new' => $goods->is_new ?? 0,
                                            'is_hot' => $goods->is_hot ?? 0,
                                            'is_discount' => $goods->is_discount ?? 0,
                                            'is_recommand' => $goods->is_recommand ?? 0,
                                            'sales' => $totalSales,
                                            'min_buy' => $goods->min_buy ?? 1,
                                            'max_buy' => $goods->max_buy ?? 0,
                                            'created_at' => $createdAt,
                                            'updated_at' => $updatedAt
                                        ];
                                        
                                        // 如果有规格，添加规格信息
                                        if ($goods->has_option == 1) {
                                            $specs = [];
                                            $options = [];
                                            
                                            // 获取规格组
                                            if (isset($specsMap[$goods->id])) {
                                                foreach ($specsMap[$goods->id] as $spec) {
                                                    $items = [];
                                                    // 获取规格项
                                                    if (isset($specItemsMap[$spec->id])) {
                                                        foreach ($specItemsMap[$spec->id] as $item) {
                                                            $items[] = [
                                                                'id' => $item->id,
                                                                'title' => $item->title ?? '',
                                                                'thumb' => $item->thumb ? ImageUrlService::processImageUrl($item->thumb) : ''
                                                            ];
                                                        }
                                                    }
                                                    
                                                    $specs[] = [
                                                        'id' => $spec->id,
                                                        'title' => $spec->title ?? '',
                                                        'items' => $items
                                                    ];
                                                }
                                            }
                                            
                                            // 获取SKU选项
                                            if (isset($optionsMap[$goods->id])) {
                                                foreach ($optionsMap[$goods->id] as $option) {
                                                    $options[] = [
                                                        'id' => $option->id,
                                                        'goods_id' => $option->goods_id,
                                                        'specs' => $option->specs ? json_decode($option->specs, true) : [],
                                                        'stock' => $option->stock ?? 0,
                                                        'price' => $option->product_price ?? '0.00',
                                                        'market_price' => $option->market_price ?? '0.00',
                                                        'cost_price' => $option->cost_price ?? '0.00',
                                                        'sku' => $option->goods_sn ?? '',
                                                        'thumb' => isset($option->thumb) ? ImageUrlService::processImageUrl($option->thumb) : ''
                                                    ];
                                                }
                                            }
                                            
                                            $result['specs'] = $specs;
                                            $result['options'] = $options;
                                        }
                                        
                                        return $result;
                                    })->filter()->values();
                            }
                            
                            \Log::info("[商家详情] 二级分类 {$secondCat->name} 商品列表构建完成", [
                                'category_id' => $secondCat->id,
                                'goods_list_count' => $goodsList->count()
                            ]);
                            
                            return [
                                'id' => $secondCat->id,
                                'name' => $secondCat->name,
                                'parent_id' => $secondCat->parent_id,
                                'thumb' => ImageUrlService::processImageUrl($secondCat->thumb),
                                'goodsList' => $goodsList->toArray()
                            ];
                        })->values();
                        
                        \Log::info("[商家详情] 一级分类 {$firstCat->name} 处理完成", [
                            'category_id' => $firstCat->id,
                            'children_count' => $children->count()
                        ]);
                        
                        return [
                            'id' => $firstCat->id,
                            'name' => $firstCat->name,
                            'thumb' => ImageUrlService::processImageUrl($firstCat->thumb),
                            'list' => $children->toArray()
                        ];
                    })->values();
                }
                
                \Log::info('[商家详情] 分类层级结构构建完成', [
                    'categories_data_count' => count($categoriesData)
                ]);
                
                // 在一级分类前面添加"全部"选项
                if (!empty($categoriesData)) {
                    // 先将 Collection 转换为数组
                    $categoriesArray = is_array($categoriesData) ? $categoriesData : $categoriesData->toArray();
                    
                    // 收集所有商品（从所有一级分类的二级分类中）
                    $allGoods = [];
                    foreach ($categoriesArray as $firstCat) {
                        foreach ($firstCat['list'] as $secondCat) {
                            $allGoods = array_merge($allGoods, $secondCat['goodsList']);
                        }
                    }
                    
                    // 去重（基于商品ID）
                    $uniqueGoods = [];
                    $goodsIds = [];
                    foreach ($allGoods as $goods) {
                        if (!in_array($goods['id'], $goodsIds)) {
                            $uniqueGoods[] = $goods;
                            $goodsIds[] = $goods['id'];
                        }
                    }
                    
                    // 构建"全部"分类项（放在数组最前面）
                    $allCategory = [
                        'id' => 0,  // 使用0作为"全部"的ID
                        'name' => '全部',
                        'thumb' => '',
                        'list' => [
                            [
                                'id' => 0,
                                'name' => '全部商品',
                                'parent_id' => 0,
                                'thumb' => '',
                                'goodsList' => $uniqueGoods
                            ]
                        ]
                    ];
                    
                    // 将"全部"添加到数组最前面
                    array_unshift($categoriesArray, $allCategory);
                    
                    // 重新赋值为数组
                    $categoriesData = $categoriesArray;
                    
                    \Log::info('[商家详情] 已添加"全部"分类', [
                        'all_goods_count' => count($uniqueGoods)
                    ]);
                }
                
            } catch (Exception $e) {
                throw new Exception("分类查询失败: " . $e->getMessage());
            }

            // 获取门店评论数据
            $commentData = Store::getCommentData($storeId);
            // 如果返回空数组，使用默认值
            if (empty($commentData)) {
                $commentData = ['average_score' => 5, 'comment_total' => 0];
            }
            
            // 查询置换类型及自提支持
            $swapTypes = $this->getStoreSwapTypes($store->id);

            $pickupInfoMap = $this->getBatchStorePickupVendors([$store->id]);
            $pickupInfo = $pickupInfoMap[$store->id] ?? [
                'supports_pickup' => false,
                'vendor_ids' => [],
                'vendors' => [],
            ];

            // 构建返回数据
            \Log::info('[商家详情] 开始构建返回数据');
            
            $data = [
                'categories' => $categoriesData,
                'store_info' => [
                    'store_id' => $store->id,
                    'store_thumb' => ImageUrlService::processImageUrl($store->thumb),
                    'store_barnner_thumb' => '', // 该字段在表中不存在
                    'store_name' => $store->store_name,
                    'operating_state' => $store->operating_state ?? 0,
                    'dispatch' => $dispatchText ?: [], // 配送方式文本数组
                    'dispatch_type' => $dispatchType ?: [2], // 配送类型
                    'delivery_information' => 1, // 默认值
                    'affiche' => $store->affiche ?? '',
                    'goods_total' => isset($storeGoods) ? $storeGoods->count() : 0, // 使用新表查询的商品总数
                    'business_hours' => ($store->business_hours_start ?? '') . '-' . ($store->business_hours_end ?? ''),
                    'store_address' => $store->address ?? '',
                    'store_mobile' => $store->mobile ?? '',
                    'store_introduce' => $store->store_introduce ?? '',
                    'lng' => $store->longitude ?? 0,
                    'lat' => $store->latitude ?? 0,
                    'specify_show' => $store->specify_show ?? 0,
                    'province_name' => $provinceName,
                    'city_name' => $cityName,
                    'district_name' => $districtName,
                    'full_address' => trim($provinceName . ' ' . $cityName . ' ' . $districtName . ' ' . ($store->address ?? '')),
                    'comment' => $commentData, // 添加评论数据
                    'swap_types' => $swapTypes,
                    'supports_pickup' => $pickupInfo['supports_pickup'] ?? false,
                    'vendor_ids' => $pickupInfo['vendor_ids'] ?? [],
                    'vendors' => $pickupInfo['vendors'] ?? [],
                ],

            ];
            
            \Log::info('[商家详情] 返回数据构建完成', [
                'categories_count' => count($categoriesData),
                'goods_total' => $data['store_info']['goods_total']
            ]);

            return response()->json([
                'code' => 200,
                'message' => '获取成功',
                'data' => $data
            ]);

        } catch (Exception $e) {
            \Log::error('[商家详情] ========== 接口异常 ==========');
            \Log::error('[商家详情] 异常信息:', [
                'error_message' => $e->getMessage(),
                'error_file' => $e->getFile(),
                'error_line' => $e->getLine(),
                'error_trace' => $e->getTraceAsString()
            ]);
            \Log::error('[商家详情] 请求参数:', [
                'store_id' => $storeId ?? 'unknown',
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'code' => 500,
                'message' => '获取失败: ' . $e->getMessage(),
                'data' => null,
                'debug_info' => [
                    'store_id' => $storeId ?? 'unknown',
                    'error_file' => $e->getFile(),
                    'error_line' => $e->getLine(),
                    'timestamp' => now()->toISOString()
                ]
            ], 500);
        }
    }

    /**
     * 获取商家分类
     * 根据sort排序，并且没有关联的店铺不显示
     *
     * @return JsonResponse
     */
    public function categories(): JsonResponse
    {
        \Log::info('[商家分类] ========== 开始处理请求 ==========');
        
        try {
            // 查询有关联店铺的商家分类，按sort排序
            \Log::info('[商家分类] 开始查询分类数据');
            
            // 先查询所有分类看看是否存在 sort=0 的
            $allCategories = StoreCategory::select(['id', 'name', 'thumb', 'sort', 'is_open'])
                ->get();
            
            \Log::info('[商家分类] 数据库中所有分类（包括未启用的）:', [
                'count' => $allCategories->count(),
                'sort_0_categories' => $allCategories->where('sort', '<=', 0)->toArray()
            ]);
            
            $categories = StoreCategory::query()
                ->where('is_open', 1) // 只查询启用的分类
                ->whereExists(function($query) {
                    $query->select(\DB::raw(1))
                        ->from('ims_yz_store')
                        ->whereColumn('ims_yz_store.category_id', 'ims_yz_store_category.id')
                        ->where('ims_yz_store.is_hide', 0)
                        ->where('ims_yz_store.operating_state', 0);
                })
                ->select(['id', 'name', 'thumb', 'sort'])
                ->get();
            
            \Log::info('[商家分类] 查询完成（启用且有门店的）:', [
                'count' => $categories->count(),
                'data' => $categories->toArray()
            ]);
            
            // 检查是否有 sort=0 的分类
            $sort0Categories = $categories->where('sort', '<=', 0);
            \Log::info('[商家分类] sort<=0 的分类:', [
                'count' => $sort0Categories->count(),
                'data' => $sort0Categories->toArray()
            ]);
            
            // 分组排序：sort > 0 的按 sort 升序，sort = 0 的排在后面
            \Log::info('[商家分类] 开始排序处理');
            
            $withSort = $categories->where('sort', '>', 0)->sortBy('sort')->values();
            $withoutSort = $categories->where('sort', '<=', 0)->sortBy('id')->values();
            
            \Log::info('[商家分类] 排序统计:', [
                'with_sort_count' => $withSort->count(),
                'with_sort_data' => $withSort->toArray(),
                'without_sort_count' => $withoutSort->count(),
                'without_sort_data' => $withoutSort->toArray()
            ]);
            
            // 合并：有排序的在前，无排序的在后
            $sortedCategories = $withSort->concat($withoutSort);
            
            \Log::info('[商家分类] 排序后的数据:', $sortedCategories->toArray());
            
            $categories = $sortedCategories->map(function($category) {
                return [
                    'id' => $category->id,
                    'name' => $category->name,
                    'thumb' => ImageUrlService::processImageUrl($category->thumb),
                    'sort' => $category->sort ?? 0
                ];
            })->toArray();
            
            \Log::info('[商家分类] 格式化后的数据:', $categories);

            // 在开头添加"全部商家"选项
            array_unshift($categories, [
                'id' => 'all',
                'name' => '全部商家',
                'thumb' => '',
                'sort' => -1
            ]);
            
            \Log::info('[商家分类] 最终返回数据:', [
                'count' => count($categories),
                'data' => $categories
            ]);

            return response()->json([
                'code' => 200,
                'message' => '获取成功',
                'data' => $categories
            ]);

        } catch (\Exception $e) {
            \Log::error('获取商家分类失败', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 500,
                'message' => '获取分类失败: ' . $e->getMessage(),
                'data' => null
            ], 500);
        }
    }

    /**
     * 搜索商家
     * 支持关键词、分类、置换类型、经纬度等条件搜索
     * 
     * 性能优化说明：
     * 1. 使用JOIN替代whereExists，减少子查询
     * 2. 批量获取评论数据和置换类型，避免N+1查询
     * 3. 优化距离计算，使用更高效的公式
     * 4. 添加查询缓存，减少重复计算
     * 5. 建议添加数据库索引：
     *    - ims_yz_store: (is_hide, operating_state, category_id, longitude, latitude)
     *    - ims_yz_store_cashier_switch_code_group_relation: (store_id, state)
     *    - ims_yz_store_cashier_switch_code_group_properties: (id, state, in_type)
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function search(Request $request): JsonResponse
    {
        \Log::info('[商家搜索] ========== 开始处理请求 ==========');
        \Log::info('[商家搜索] 接收到的原始请求:', $request->all());
        
        try {
            // 获取搜索参数
            $page = max(1, (int) $this->getParam($request, 'page', 1));
            $limit = max(1, (int) $this->getParam($request, 'limit', 10));
            $keyword = trim($this->getParam($request, 'keyword', ''));
            $categoryId = $this->getParam($request, 'category_id');
            $swapSupport = $this->getParam($request, 'swap_support'); // 置换支持类型
            $lat = $this->getParam($request, 'lat');
            $lng = $this->getParam($request, 'lng');
            
            // 设置默认经纬度（武汉江汉路）
            if (empty($lat)) $lat = 30.584;
            if (empty($lng)) $lng = 114.285;

            $userLat = (float) $lat;
            $userLng = (float) $lng;
            
            \Log::info('[商家搜索] 解析后的参数:', [
                'page' => $page,
                'limit' => $limit,
                'keyword' => $keyword,
                'category_id' => $categoryId,
                'swap_support' => $swapSupport,
                'lat' => $userLat,
                'lng' => $userLng
            ]);

            // 构建基础查询
            $query = Store::query()
                ->select([
                    'ims_yz_store.id', 'ims_yz_store.store_name', 'ims_yz_store.thumb', 'ims_yz_store.address', 'ims_yz_store.mobile', 
                    'ims_yz_store.longitude', 'ims_yz_store.latitude', 'ims_yz_store.created_at', 'ims_yz_store.category_id', 'ims_yz_store.dispatch_type'
                ])
                ->where('ims_yz_store.is_hide', 0)
                ->where('ims_yz_store.operating_state', 0);

            // 关键词搜索
            if (!empty($keyword)) {
                $query->where(function($q) use ($keyword) {
                    $q->where('ims_yz_store.store_name', 'like', "%{$keyword}%")
                      ->orWhere('ims_yz_store.address', 'like', "%{$keyword}%")
                      ->orWhere('ims_yz_store.store_introduce', 'like', "%{$keyword}%");
                });
            }

            // 分类筛选
            if (!empty($categoryId) && $categoryId !== 'all') {
                $query->where('ims_yz_store.category_id', $categoryId);
            }

            // 置换支持筛选 - 使用JOIN优化
            if (!empty($swapSupport)) {
                $query->join('ims_yz_store_cashier_switch_code_group_relation as relation', 'ims_yz_store.id', '=', 'relation.store_id')
                      ->join('ims_yz_store_cashier_switch_code_group_properties as properties', 'relation.group_propertie_id', '=', 'properties.id')
                      ->where('relation.state', 1)
                      ->where('properties.state', 1)
                      ->where('properties.in_type', $swapSupport)
                      ->distinct(); // 避免重复结果
            }

            // 优化距离计算 - 使用更高效的公式
            $query->selectRaw(
                "(6371 * acos(cos(radians(?)) * cos(radians(ims_yz_store.latitude)) * cos(radians(ims_yz_store.longitude) - radians(?)) + sin(radians(?)) * sin(radians(ims_yz_store.latitude)))) AS distance",
                [$userLat, $userLng, $userLat]
            );

            // 按距离排序
            $query->orderBy('distance', 'asc');

            // 分页查询
            \Log::info('[商家搜索] 开始执行查询');
            
            $total = (clone $query)->count();
            $totalPages = ceil($total / $limit);
            $stores = $query->offset(($page - 1) * $limit)->limit($limit)->get();
            
            \Log::info('[商家搜索] 查询完成', [
                'total' => $total,
                'total_pages' => $totalPages,
                'stores_count' => $stores->count()
            ]);

            // 批量获取分类信息
            $categoryIds = $stores->pluck('category_id')->filter()->unique()->toArray();
            $categories = [];
            if (!empty($categoryIds)) {
                $categories = StoreCategory::query()
                    ->whereIn('id', $categoryIds)
                    ->pluck('name', 'id')
                    ->toArray();
                    
                \Log::info('[商家搜索] 分类信息查询完成', ['categories' => $categories]);
            }

            // 批量获取评论数据 - 避免N+1查询
            $storeIds = $stores->pluck('id')->toArray();
            \Log::info('[商家搜索] 提取门店ID列表', ['store_ids' => $storeIds]);
            
            $commentDataMap = [];
            if (!empty($storeIds)) {
                $commentDataMap = Store::getCommentDataBatch($storeIds);
                \Log::info('[商家搜索] 评论数据查询完成', ['comment_data_map' => $commentDataMap]);
            }

            // 批量获取置换类型 - 避免N+1查询
            $swapTypesMap = [];
            if (!empty($storeIds)) {
                $swapTypesMap = $this->getStoreSwapTypesBatch($storeIds);
            }

            // 批量获取供货商信息（用于判断上门自提）
            $pickupVendorsMap = [];
            if (!empty($storeIds)) {
                $pickupVendorsMap = $this->getBatchStorePickupVendors($storeIds);
                \Log::info('[商家搜索] 供货商信息查询完成', ['pickup_vendors_map' => $pickupVendorsMap]);
            }

            // 格式化结果
            \Log::info('[商家搜索] 开始格式化结果');
            
            $storeIndex = 0;
            $result = $stores->map(function ($store) use ($categories, $commentDataMap, $swapTypesMap, $pickupVendorsMap, &$storeIndex) {
                $storeIndex++;
                
                \Log::info("[商家搜索] 处理门店 #{$storeIndex}", [
                    'store_id' => $store->id,
                    'store_name' => $store->store_name,
                    'dispatch_type_raw' => $store->dispatch_type
                ]);
                
                $dispatchType = is_string($store->dispatch_type) ? json_decode($store->dispatch_type, true) : $store->dispatch_type;
                $dispatchText = $this->getDispatchText($dispatchType);
                $categoryName = isset($categories[$store->category_id]) ? $categories[$store->category_id] : '未分类';
                
                \Log::info("[商家搜索] 门店 #{$storeIndex} 配送信息", [
                    'dispatch_type_parsed' => $dispatchType,
                    'dispatch_text' => $dispatchText
                ]);
                
                // 从批量数据中获取
                $swapTypes = $swapTypesMap[$store->id] ?? [];
                $commentData = $commentDataMap[$store->id] ?? ['average_score' => 5, 'comment_total' => 0];
                $pickupVendors = $pickupVendorsMap[$store->id] ?? ['supports_pickup' => false, 'vendor_ids' => [], 'vendors' => []];
                
                \Log::info("[商家搜索] 门店 #{$storeIndex} 其他信息", [
                    'swap_types' => $swapTypes,
                    'comment_data' => $commentData,
                    'pickup_vendors' => $pickupVendors
                ]);
                
                $formattedStore = [
                    'id'             => $store->id,
                    'store_name'     => $store->store_name,
                    'thumb'          => ImageUrlService::processImageUrl($store->thumb),
                    'address'        => $store->address,
                    'mobile'         => $store->mobile,
                    'longitude'      => $store->longitude,
                    'latitude'       => $store->latitude,
                    'created_at'     => $store->created_at,
                    'category_id'    => $store->category_id,
                    'category_name'  => $categoryName,
                    'category_thumb' => '',
                    'distance'       => $store->distance,
                    'distance_text'  => $this->formatDistance($store->distance),
                    'dispatch_type'  => $dispatchType,
                    'dispatch'       => $dispatchText,
                    'swap_types'     => $swapTypes,
                    'average_score'  => $commentData['average_score'] ?? 5,
                    'comment_total'  => $commentData['comment_total'] ?? 0,
                    'supports_pickup' => $pickupVendors['supports_pickup'],
                    'vendor_ids'     => $pickupVendors['vendor_ids'],
                    'vendors'        => $pickupVendors['vendors'],
                ];
                
                \Log::info("[商家搜索] 门店 #{$storeIndex} 格式化完成", [
                    'formatted_store' => $formattedStore
                ]);
                
                return $formattedStore;
            })->toArray();

            // 分页信息
            $pagination = [
                'total'       => $total,
                'page'        => $page,
                'limit'       => $limit,
                'total_pages' => $totalPages,
            ];
            
            \Log::info('[商家搜索] 准备返回结果', [
                'stores_count' => count($result),
                'pagination' => $pagination
            ]);

            return response()->json([
                'code' => 200,
                'message' => '搜索成功',
                'data' => [
                    'stores'     => $result,
                    'pagination' => $pagination,
                ],
            ]);

        } catch (\Exception $e) {
            \Log::error('[商家搜索] ========== 接口异常 ==========');
            \Log::error('[商家搜索] 异常信息:', [
                'error_message' => $e->getMessage(),
                'error_file' => $e->getFile(),
                'error_line' => $e->getLine(),
                'error_trace' => $e->getTraceAsString()
            ]);
            \Log::error('[商家搜索] 请求参数:', $request->all());
            
            return response()->json([
                'code' => 500,
                'message' => '搜索失败: ' . $e->getMessage(),
                'data' => [
                    'stores'     => [],
                    'pagination' => [
                        'total'       => 0,
                        'page'        => $page ?? 1,
                        'limit'       => $limit ?? 10,
                        'total_pages' => 0,
                    ],
                ],
            ], 500);
        }
    }
}

